<template>
    <basic-container>
      <el-row :span="24">
        <el-col :xs="24"
                :sm="24"
                :md="5"
                class="user__tree">

          <avue-tree :option="navTreeOption"
                     :data="deptTreeData"
                     @node-click="nodeClick"></avue-tree>
        </el-col>
        <el-col :xs="24"
                :sm="24"
                :md="19"
                class="user__main">
          <chc-datagrid :option="option"
                     ref="crud"
                     v-model="form"
                     :page="page"
                     @on-load="getList"
                     :table-loading="listLoading"
                     @search-change="handleFilter"
                     @refresh-change="handleRefreshChange"
                     @row-update="update"
                     @row-save="create"
                     :before-open="handleOpenBefore"
                     :data="list">
            <template slot="menuLeft">
              <el-button v-if="permissions['sys.user.add']"
                         class="filter-item"
                         @click="handleCreate"
                         size="small"
                         type="primary"
                         icon="el-icon-edit">添加
              </el-button>
            </template>
            <template slot="username"
                      slot-scope="scope">
              <span>{{scope.row.username}}</span>
            </template>
            <template slot="role"
                      slot-scope="scope">
              <span v-for="(role,index) in scope.row.roleList"
                    :key="index">
                <el-tag>{{role.name}} </el-tag>&nbsp;&nbsp;
              </span>
            </template>
            <template slot="deptId"
                      slot-scope="scope">
              {{scope.row.deptName}}
            </template>
            <template slot="orgId"
                      slot-scope="scope">
              {{scope.row.orgName}}
            </template>
            <template slot="isLocked"
                      slot-scope="scope">
              {{scope.row.isLocked?'是':'否'}}
            </template>
            <template slot="isActive"
                      slot-scope="scope">
              {{scope.row.isActive?'是':'否'}}
            </template>
            <template slot="isAdmin"
                      slot-scope="scope">
              {{scope.row.isAdmin?'是':'否'}}
            </template>
            <template slot="menu"
                      slot-scope="scope">
              <el-button v-if="permissions['sys.user.edit']"
                         size="small"
                         type="text"
                         icon="el-icon-edit"
                        plain
                         @click="handleUpdate(scope.row,scope.index)">编辑
              </el-button>
              <el-button v-if="permissions['sys.user.delete']"
                         size="small"
                         type="text"
                         icon="el-icon-delete"
                        plain
                         @click="deletes(scope.row,scope.index)">删除
              </el-button>
              <el-button v-if="permissions['sys.user.orgAuth'] && scope.row.dataScope=='3'"
                        size="small"
                        type="text"
                        icon="el-icon-plus"
                        plain
                        @click="handleOrgPermission(scope.row,scope.index)"
                        >机构权限
              </el-button>
              <el-button v-if="permissions['sys.user.resetPwd']"
                         size="small"
                         type="text"
                         icon="el-icon-edit"
                        plain
                         @click="handleResetPassword(scope.row,scope.index)">重置密码
              </el-button>
            </template>
            <template slot="deptIdForm"
                      slot-scope="scope">
              <avue-input v-model="form.deptId"
                               type="tree"
                               placeholder="请选择所属部门"
                               :dic="deptTreeData"
                               :props="deptProps"></avue-input>
            </template>
            <template slot="orgIdForm"
                      slot-scope="scope">
              <chc-select v-model="form.orgId"
                               type="select"
                               placeholder="请选择所属机构"
                               :remote="true"
                               dicUrl="/sys/org/companyList">

                               </chc-select>
            </template>
            <template slot="roleForm"
                      slot-scope="scope">
              <chc-select v-model="role"
                                multiple
                                placeholder="请选择角色"
                                :dic="rolesOptions"
                                :props="roleProps"></chc-select>
            </template>
          </chc-datagrid>
        </el-col>
      </el-row>
      <el-dialog title="设置机构权限"
                :visible.sync="orgPermDlgVisible">
        <auth-tree-table :show-header="false" ref="authTable" :height="400"  :data="orgPermList" :columns="orgPermColumns" row-key="id"></auth-tree-table>
        <!-- <avue-tree-table :option="orgPermOption" :data="orgPermList"></avue-tree-table> -->
        <div slot="footer"
            class="dialog-footer">
          <el-button type="primary"
                    @click="updateOrgPermession(userId)">更 新
          </el-button>
        </div>
      </el-dialog>
      <el-dialog title="重置密码" :visible.sync="resetPasswordDlgVisible" width="40%">
          <el-form :model="passwordForm"
                    :rules="passwordFormRules"
                    ref="passwordForm"
                    label-width="100px">
            <el-form-item label="新密码"
                          prop="newPassword1">
              <el-input type="password"
                        v-model="passwordForm.newPassword1"
                        auto-complete="off"></el-input>
            </el-form-item>
            <el-form-item label="确认新密码"
                          prop="newPassword2">
              <el-input type="password"
                        v-model="passwordForm.newPassword2"
                        auto-complete="off"></el-input>
            </el-form-item>
          </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary"
                      @click="submitPasswordForm()">提交
          </el-button>
          <el-button @click="resetPasswordForm()">重置</el-button>
        </div>

      </el-dialog>
    </basic-container>

</template>

<script>
  import {addObj, delObj, fetchList, getObj, putObj,fetchOrgAuthTree,saveOrgAuth,resetPwd} from "@/modules/sys/api/user";
  import {listByOrg as roleListByOrg} from "@/modules/sys/api/role";
  import {fetchOrgTree} from "@/modules/sys/api/org";
  import {fetchDeptTree} from "@/modules/sys/api/dept";
  import {tableOption} from './user';
  import {mapGetters} from "vuex";
  import {constants} from 'fs';
  import {connect} from 'tls';
  import authTreeTable from '@/components/auth-tree-table';
	
  export default {
    name: "table_user",
    components: {authTreeTable },
    data() {
      var validatePass= (rule, value, callback)=> {
        if (value !== this.passwordForm.newPassword1) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      }
      return {
        navTreeOption: {
          nodeKey: 'id',
          addBtn: false,
          menu: false,
          props: {
            label: 'label',
            value: 'id'
          }
        },
        option: tableOption,
        checkedKeys: [],
        roleProps: {
          label: "name",
          value: 'id'
        },
        deptTreeData: [],
        deptProps: {
          label: "label",
          value: 'id',
        },
        orgTreeData: [],
        orgProps: {
          label: "label",
          value: 'id',
        },
        page: {
          total: 0, // 总页数
          currentPage: 1, // 当前页数
          pageSize: 20, // 每页显示多少条,
          isAsc: false//是否倒序
        },
        list: [],
        listLoading: false,
        role: [],
        form: {
          isActive : undefined,
          orgId : undefined
        },
        rolesOptions: [],
        orgPermDlgVisible: false,
        orgPermColumns:[
            {
              label: '机构',
              prop: 'label',
              width: 200
            },
            {
              label: '权限',
              prop: 'options',
            }
          ],
        orgPermList:[],
        //重置密码
        passwordForm: {
          newPassword1: '',
          newPassword2: ''
        },
        passwordFormRules: {
          newPassword1: [{required: false, min: 6, message: '不少于6位', trigger: 'change'}],
          newPassword2: [{required: false, validator: validatePass, trigger: 'blur'}]
        },
        resetPasswordDlgVisible: false
      }
    },
    computed: {
      ...mapGetters(["permissions","userInfo"]),
      formOrgId(){
        return this.form.orgId;
      }
    },
    watch: {
      role() {
        this.form.role = this.role
      },
      formOrgId() {
        this.handleOrgChange();
      }
    },
    created() {
      this.init();
    },
    methods: {
      init() {
        fetchDeptTree({
          orgId: this.userInfo.orgId
        }).then(response => {
          this.deptTreeData = response.data.data;
        });
      },
      nodeClick(data) {
        this.page.page = 1;
        this.getList(this.page, {deptId: data.id});
      },
      getList(page, params) {
        this.listLoading = true;
        fetchList(Object.assign({
          current: page.currentPage,
          size: page.pageSize,
          orgId:this.userInfo.orgId
        }, params)).then(response => {
          this.list = response.data.data.records;
          this.page.total = response.data.data.total
          this.listLoading = false;
        });
      },
      // getNodeData(data) {
      //   deptRoleList().then(response => {
      //     this.rolesOptions = response.data.data;
      //   });
      // },
      handleFilter(param) {
        this.page.page = 1;
        this.getList(this.page, param);
      },
      handleRefreshChange() {
        this.getList(this.page)
      },
      handleCreate() {
        this.$refs.crud.rowAdd();
        this.resetForm();
      },
      handleOrgChange() {
        if (this.form.orgId){
          roleListByOrg(this.form.orgId).then(response => {
            this.rolesOptions = response.data.data;
          });
        }
        else {
          this.rolesOptions=[];
        }

      },
      handleOpenBefore(show, type) {
        window.boxType = type;
        //this.handleDept();
        if (['edit', 'views'].includes(type)) {
          this.role = [];
          for (var i = 0; i < this.form.roleList.length; i++) {
            this.role[i] = this.form.roleList[i].id;
          }

          roleListByOrg(this.form.orgId).then(response => {
            this.rolesOptions = response.data.data;
          });
          fetchOrgTree().then(response => {
            this.orgTreeData = response.data.data;
          });

        } else if (type === 'add') {
          this.role = [];
        }
        show();
      },
      handleUpdate(row, index) {
        this.$refs.crud.rowEdit(row, index);
        this.form.password = undefined
      },
      create(row, done, loading) {
        addObj(this.form).then(() => {
          this.getList(this.page);
          done();
          this.$notify({
            title: "成功",
            message: "创建成功",
            type: "success",
            duration: 2000
          });
        }).catch(() => {
          loading();
        });
      },
      update(row, index, done, loading) {
        putObj(this.form).then(() => {
          this.getList(this.page);
          done();
          this.$notify({
            title: "成功",
            message: "修改成功",
            type: "success",
            duration: 2000
          });
        }).catch(() => {
          loading();
        });
      },
      deletes(row, index) {
        this.$confirm(
          "此操作将永久删除该用户(用户名:" + row.username + "), 是否继续?",
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning"
          }
        ).then(() => {
          delObj(row.id)
            .then(() => {
              this.list.splice(index, 1);
              this.$notify({
                title: "成功",
                message: "删除成功",
                type: "success",
                duration: 2000
              });
            })
            .catch(() => {
              this.$notify({
                title: "失败",
                message: "删除失败",
                type: "error",
                duration: 2000
              });
            });
        });
      },
      resetForm() {
        this.form = {
          isActive: true,
          isLocked: false,
          orgId: this.userInfo.orgId
        }
      },
      handleOrgPermission(row) {
        let me = this;
        fetchOrgAuthTree(row.id)
          .then(response => {
            me.userId = row.id
            me.orgPermList = response.data.data
            me.orgPermDlgVisible = true
          })
      },

      updateOrgPermession(userId){
        let data=[];
        let visit = function(row){
          let row1 = {id: row.id,options:row.options};
          data.push(row1);
          if (row.children){
            row.children.forEach(visit)
          }
        }
        this.orgPermList.forEach(visit);
        saveOrgAuth(userId,data)
        //: JSON.stringify(this.orgPermList)
          .then(response => {
            this.$notify({
                title: "成功",
                message: "设置权限成功",
                type: "success",
                duration: 2000
              })
            this.orgPermDlgVisible = false
            })
          .catch(() => {
            this.$notify({
              title: "失败",
              message: "设置权限失败",
              type: "error",
              duration: 2000
            })
          })

      },
      handleResetPassword(row) {
        this.resetPasswordForm()
        this.userId = row.id
        this.resetPasswordDlgVisible = true
      },
      submitPasswordForm() {
        this.$refs['passwordForm'].validate(valid => {
          if (valid) {
            resetPwd(this.userId,this.passwordForm.newPassword1)
              .then(response => {
                if (response.data.code===0) {
                  this.$notify({
                    title: '成功',
                    message: '重置密码成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.resetPasswordDlgVisible = false
                } else {
                  this.$notify({
                    title: '失败',
                    message: response.data.msg,
                    type: 'error',
                    duration: 2000
                  })
                }
              })
              // .catch(() => {
              //   this.$notify({
              //     title: '失败',
              //     message: '重置密码失败',
              //     type: 'error',
              //     duration: 2000
              //   })
              //   return false;
              // })
          } else {
            return false
          }
        })
      },
      resetPasswordForm() {
        this.passwordForm={
          newPassword1: '',
          newPassword2: ''
        }
      },
    }
  };
</script>
<style lang="scss">
  .user {
    height: 100%;

    &__tree {
      padding-top: 3px;
      padding-right: 10px;
    }

    &__main {
      .el-card__body {
          padding: 0px;
      }
    }
    .el-col {
      margin-bottom: 0px;
    }
}
</style>

